<template>
  <div class="flex w-full">
    <a-scrollbar style="height: 72vh; overflow-y: auto">
      <div class="flex-1">
        <a-tree
          v-if="treeData.length"
          ref="treeRef"
          v-model:checked-keys="checkedKeys"
          v-model:half-checked-keys="halfCheckedKeys"
          checkable
          multiple
          :data="treeData"
          :field-names="{ key: 'id', title: 'title', icon: 'ic' }"
          action-on-node-click="expand"
          only-check-leaf
        >
        </a-tree>
      </div>
    </a-scrollbar>
  </div>
</template>
<script setup lang="tsx">
  import { TreeInstance } from '@arco-design/web-vue';

  import { listWebModuleApi } from '@/api/system/role';

  const props = defineProps({
    currentId: {
      type: String,
      default: () => null,
    },
  });

  const treeData = ref([]);
  const treeRef = ref<TreeInstance>();
  const checkedKeys = ref<string[]>([]);
  const halfCheckedKeys = ref<string[]>([]);

  const listModule = async (currentId: string) => {
    const res = await listWebModuleApi(currentId);
    if (res) {
      treeData.value = res.webModules as any;
      checkedKeys.value = res.checkedWebModuleIds;
    }
  };

  const submit = async () => {
    return {
      webModuleIds: checkedKeys.value.concat(halfCheckedKeys.value),
    };
  };

  watch(
    () => props.currentId,
    (currentId) => {
      listModule(currentId);
    },
    {
      immediate: true,
    }
  );

  defineExpose({
    submit,
  });
</script>
